/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.ueditor.service;

import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.guoyu.project.common.ueditor.UeditorDefaultConfig;
import com.guoyu.project.common.ueditor.model.ActionType;
import com.guoyu.project.common.ueditor.model.UeditorResult;

/**
 * @author: libo Date: 17-6-21 Time: 下午2:29
 * @version: \$Id$
 */
@Service
public class ListFileHandler extends AbstractHandler implements UeditorHandler {
    @Override
    public UeditorResult handle(HttpServletRequest request, MultipartFile uploadFile) {
        File dirFile = new File(getPhysicalPathPre() + getRelativePathPre());
        Collection<File> list = FileUtils.listFiles(dirFile, new SuffixFileFilter(getFileSuffixNames()),
                TrueFileFilter.INSTANCE);
        int start = NumberUtils.toInt(request.getParameter("start"), 0);

        UeditorResult result = UeditorResult.success();
        if (start >= 0 && start < list.size()) {
            Object[] fileList = Arrays.copyOfRange(list.toArray(), start, start + UeditorDefaultConfig.LIST_FILE_SIZE);
            result.setList(convert(fileList));
        }
        result.setStart(start);
        result.setTotal(list.size());
        return result;
    }

    public String[] getFileSuffixNames() {
        return UeditorDefaultConfig.ALL_FILE_SUFFIX_NAMES;
    }

    @Override
    public ActionType getActionType() {
        return ActionType.listfile;
    }

    private List<UeditorResult> convert(Object[] fileList) {
        List<UeditorResult> ueditorResultList = Lists.newArrayListWithCapacity(fileList.length);
        UeditorResult result;
        File file;

        for (Object obj : fileList) {
            if (obj == null) {
                break;
            }
            file = (File) obj;
            result = UeditorResult.success();
            result.setUrl(getUrl(StringUtils.replace(file.getPath(), getPhysicalPathPre(), "")));
            ueditorResultList.add(result);
        }
        return ueditorResultList;
    }
}
